﻿/*
Copyright (C) 2015 Dieter Vandroemme


Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace RandomUtils {
    /// <summary>
    /// <para>A super-simple key value store implementation. Basically a wrapper around ConcurrentDictionary.</para>
    /// <para>You can use the instance if you want one general KeyValueStore.</para>
    /// </summary>
    public class KeyValueStore : IDisposable {
        private static KeyValueStore _instance;

        private bool _isDisposed;
        private ConcurrentDictionary<object, object> _store = new ConcurrentDictionary<object, object>();

        /// <summary>
        /// The current size of the store.
        /// </summary>
        public int Size { get { return _store.Count; } }

        /// <summary>
        /// Returns all the keys.
        /// </summary>
        public ICollection<object> Keys { get { return _store.Keys; } }

        /// <summary>
        /// Returns all the values.
        /// </summary>
        public ICollection<object> Values { get { return _store.Values; } }

        /// <summary>
        /// </summary>
        public bool IsDisposed { get { return _isDisposed; } }

        /// <summary>
        /// You can use the instance if you want one general KeyValueStore.
        /// </summary>
        /// <returns></returns>
        public static KeyValueStore GetInstance() {
            if (_instance == null || _instance.IsDisposed) _instance = new KeyValueStore();
            return _instance;
        }

        /// <summary>
        /// Uses a uniquely generated key, based on a random that uses a new guid hash code for a seed.
        /// </summary>
        /// <param name="value"></param>
        /// <returns>The generated key.</returns>
        public int Add(object value) {
            int key;
            do {
                var random = new Random(Guid.NewGuid().GetHashCode());
                key = random.Next();
            }
            while (_store.ContainsKey(key));
            AddOrUpdate(key, value);
            return key;
        }

        /// <summary>
        /// Adds or updated the key value pair.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void AddOrUpdate(object key, object value) { _store.AddOrUpdate(key, value, (k, v) => value); }

        /// <summary>
        /// Removes a key value pair if the key was found.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(object key) {
            object value;
            return _store.TryRemove(key, out value);
        }

        /// <summary>
        /// Clears the store.
        /// </summary>
        public void Clear() { _store.Clear(); }

        /// <summary>
        /// Returns if the store contains a key value pair for the given key.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Contains(object key) { return _store.ContainsKey(key); }

        /// <summary>
        /// Returns a value for a given key. If it was not found an exception will be thrown.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(object key) {
            object value;
            _store.TryGetValue(key, out value);
            return (T)value;
        }

        /// <summary>
        /// </summary>
        public void Dispose() {
            if (!_isDisposed) {
                _isDisposed = true;
                _store = null;
            }
        }
    }
}
